package tianwang.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileUtil {
	
	public static void saveFile(String fileName, String content,String path) throws Exception{
		BufferedWriter bw = null;
		String name = path + File.separator + fileName + ".out.txt";
		try{
			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(name)), "UTF-8"));
			bw.append(content);
			bw.flush();
		}finally{
			if(bw != null){
				bw.close();
				bw = null;
			}
		}
	}
	public static void saveFile(String fileName, String content) throws Exception{
		saveFile(fileName, content, "out");
	}
	
	public static String getContent(String fileName, String charsetName) throws Exception{
		BufferedReader br = null;
		String name =fileName.indexOf(File.separator) == -1? "in" + File.separator + fileName:fileName;
		StringBuilder sb = new StringBuilder();
		try{
			br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(name)),charsetName));
			String line = null;
			while((line = br.readLine()) != null){
				sb.append(line);
				sb.append("\n");
			}
			
			return new String(sb.toString().getBytes(charsetName),"UTF-8");
		}finally{
			if(br != null){
				br.close();
				br = null;
			}
		}
	}
	
	
	public static String getContent(String fileName) throws Exception{
		return getContent(fileName, "UTF-8");
	}
}
